package XML.DOM4J;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Test {
    Document document = null;

    public Test(){
        SAXReader reader = new SAXReader();
        try {
//            document = reader.read("/XML/DOM4J/phone.xml");
            document = reader.read(this.getClass().getResourceAsStream("/XML/DOM4J/phone.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public void show(){
        Element root = document.getRootElement();
        List<Element> brands = root.elements();
        for (Element brand : brands) {
            String brandName = brand.attributeValue("name");
            System.out.println(brandName);
            //获取孩子
            List<Element> types = brand.elements();
            for (Element type : types) {
                System.out.println("\t"+type.attributeValue("name"));
            }
        }

    }

    public void remove() {
        Element root = document.getRootElement();
        List<Element> brands = root.elements();
        for (Element brand : brands) {
            String brandName = brand.attributeValue("name");
            if (brandName.equals("苹果")) {
                brand.getParent().remove(brand);
                sava();
                break;
            }
        }
    }
    public void add(){
        //获取根节点
        Element root = document.getRootElement();
        Element brand = root.addElement("Brand");
        brand.addAttribute("name","三星");
        Element type = root.addElement("Type");
        type.addAttribute("name","note3");
        sava();
    }

    public void sava()  {
        //设置保存格式
        OutputFormat format = new OutputFormat();
        format.setEncoding("utf-8");
        //保存
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileWriter("f:\\J19\\Test1\\src\\XML\\DOM4J\\phone.xml"),format);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Test test = new Test();
        test.show();
        test.add();
        test.remove();
        System.out.println("--------");
        test.show();
    }

}
